import { Button, Card, Checkbox, Form, message, Modal, Radio, Row, Col, Select, Input, InputNumber, DatePicker } from "antd";
import { connect } from "dva";
import React, { PureComponent } from "react";
import { transferOption } from "@/utils/common";
import DealerDetailModal from './dealDetailModal'
import LockListModal from './lockListModal'
import moment from 'moment';
const FormItem = Form.Item;

@connect(({ common2, loading, user }) => ({
  common2,
  loading: loading.models.common2,
  currentUser: user.currentUser,
}))
export default class dealRiskManageModal extends PureComponent {
  formRef = React.createRef();
  state = {
    data: '',//经销商风险数据
    buttonLoading: false,
    dealDetailModalVisible: false,
    riskStatus: 0,//经销商
    detailModelData: {},//经销商详细信息
    lockListModalVisible: false,//锁车清单弹窗
    dealerLimitData: '',//经销商额度信息：含经销商组织id，经销商编码以及经销商额度表uuid，以及填写的经销商额度,车辆vin
    limitValueDisabled: false,//额度默认为可修改
  };

  componentDidMount() {
    this.props.onRef(this)
  }

  setData = (data) => {
    const status = data.riskStatus;
    this.setState({
        data: data,
        riskStatus: status,
        limitValueDisabled: data.limitValue ? true : false
    })
    setTimeout(()=>{
    this.formRef.current.setFieldsValue({
      dealerName: data.dealerName,
      riskStatus: data.riskStatus,
      limitValue: data.limitValue ? data.limitValue : undefined,
      endDate: data.endDate ? moment(data.endDate, 'YYYY-MM-DD HH:mm:ss') : undefined
    });
  }, 50)
  }
  isBeforeCurrentTime = (time)=>{
    var currentDate = new Date(); // 获取当前日期和时间
    var inputDate = new Date(time); // 将输入的时间转换成日期格式
    
    return inputDate < currentDate; // 返回结果
  }
  ok = () => {
    const {data}=this.state;
    this.formRef.current.validateFields().then(values => {
      if(values.endDate && this.isBeforeCurrentTime(values.endDate)){
        message.warning("锁车时间为当前时间之前的时间，请重新设置时间!");
        return;
      }
      const obj = values;
       const params = {
        uuid: data.uuid,
        orgId: data.orgId,
        dealerCode: data.dealerCode,
        limitValue: values.limitValue,
        riskStatus: values.riskStatus,
        endDate: values.endDate? moment(values.endDate).format('YYYY-MM-DD HH:mm:ss') : undefined
       }
       this.props.dispatch({
        type: 'creditCar/postObjWithRes',
        payload: {
          url: '/mscreditbusiness/dealer/limit/set', 
          ...params
        },
        callback: (res) => {
          const { statusCode, data, statusMessage } = res;
          if (statusCode == '0') {
            message.success(statusMessage);
            this.close();
          }
        },
      })
    });
  };

  setLoading = (flag) => {
    this.setState({
      buttonLoading: flag,
    });
  };

  close = () => {
    const { form, changeVisible } = this.props
    this.setState({
      detailModelData: {}
    })
    this.formRef.current.resetFields();
    changeVisible()
  };
  handleDealer =()=>{
    const {data}=this.state;
    this.props.dispatch({
      type: 'creditCar/postDataWithRes',
      payload: {
        url: '/mscreditbusiness/dealer/detail', 
        dealerCode: data.dealerCode
      },
      callback: (res) => {
        const { statusCode, data } = res;
        if (statusCode === '0') {
          this.setState({
            detailModelData: res.data
          })
        }
      },
    })
    this.setState({
      dealDetailModalVisible: true
    })
    this.close();
  }
  changeLockListModalVisible = (flag) => {
    if (flag) {
      this.setState({
        lockListModalVisible: false,
      });
    } else {
      this.setState({
        lockListModalVisible: false,
      });
    }
  };
  handleLock =()=>{
    const {data}=this.state;
    this.formRef.current.validateFields().then(values => {
      const obj = values;
      if(values.limitValue == 0 || !values.limitValue){
        message.warning("请先填写额度!");
        return
      }
       const params = {
        uuid: data.uuid,
        orgId: data.orgId,
        dealerCode: data.dealerCode,
        dealerName: data.dealerName,
        limitValue: values.limitValue,
       }
       this.setState({
        dealerLimitData: params,
        lockListModalVisible: true,
      })
    });
  }
  renderSimpleForm() {
    const { modalVisible,fieldList,checked} = this.props;
    const { buttonLoading,riskStatus, dealerLimitData, lockListModalVisible,limitValueDisabled} = this.state;
    const footer = (
      <div>
        <Button onClick={this.close}>取消</Button>
        <Button loading={buttonLoading} onClick={this.ok} type="primary">
          确定
        </Button>
      </div>
    );
    return (
      <div>
      <Modal
        footer={footer}
        title="经销商风险管理"
        visible={modalVisible}
        onCancel={this.close}
        style={{ top: 50}}
      >
        <div style={{ marginLeft: 20 }}>
        <Form  ref={this.formRef} >
          <Row gutter={24}>
            <Col span={20}>
           <FormItem
              name={"dealerName"}
              label={"经销商名称"}
             >
             <Input  bordered={false}/>
            </FormItem >
            </Col>
            <Col span={4}>
              <div style={{padding: '4px'}}>
            <a onClick={() => this.handleDealer()}>详情</a>
            </div>
            </Col>
          </Row>
           <FormItem
              name={"riskStatus"}
              label={"经销商风险状态"}
             >
             <Radio.Group  onChange={e => {
                      this.setState(
                        {
                          riskStatus: e.target.value
                        },
                      );
                    }}>
               <Radio value={0}>正常 </Radio>
               <Radio value={1}>高风险 </Radio>
             </Radio.Group>
           </FormItem >
           {riskStatus == '1' &&(
           <FormItem
              name={"limitValue"}
              label={"额度（%）"}
              rules={[{ required: true, message: '请填写额度' }]}
              required
             >
             <InputNumber min={1} max={100} precision={0} disabled={limitValueDisabled}/>
          </FormItem >
          )}
           {riskStatus == '1' &&(
          <FormItem
              name={"endDate"}
              label={"结束时间"}
             >
             <DatePicker
                  placeholder="请选择"
                  showTime
                  format="YYYY-MM-DD HH:mm:ss"
                />
          </FormItem >
         )}
        </Form>
        {riskStatus == '1' &&(
             <div style={{padding: '4px'}}>
             <a onClick={() => this.handleLock()}>锁车清单</a>
             </div>
         )}
        </div>
      </Modal>
      <DealerDetailModal
           changeVisible={() => {
            this.setState({ dealDetailModalVisible: false });
          }}
            modalVisible={this.state.dealDetailModalVisible}
            dispatch={this.props.dispatch}
            detailModelData={this.state.detailModelData}
          />
        {lockListModalVisible ? (<LockListModal
            changeriskLogModalVisible={this.changeLockListModalVisible}
            dispatch={this.props.dispatch}
            dealerLimitData={this.state.dealerLimitData}
          />) :null}
      </div>
    );
  }

  render() {
    return this.renderSimpleForm();
  }
}
